- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path2. Add Two Numbers.go
39 lines (35 loc) · 701 Bytes
/
2. Add Two Numbers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// ListNode define
typeListNode= structures.ListNode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
funcaddTwoNumbers(l1*ListNode, l2*ListNode) *ListNode {
head:=&ListNode{Val: 0}
n1, n2, carry, current:=0, 0, 0, head
forl1!=nil||l2!=nil||carry!=0 {
ifl1==nil {
n1=0
} else {
n1=l1.Val
l1=l1.Next
}
ifl2==nil {
n2=0
} else {
n2=l2.Val
l2=l2.Next
}
current.Next=&ListNode{Val: (n1+n2+carry) %10}
current=current.Next
carry= (n1+n2+carry) /10
}
returnhead.Next
}